//
//  ShareFreeListenVc.swift
//  TianTianBiTing
//
//  Created by Gox mac 2 on 2019/3/4.
//  Copyright © 2019 Gox_WallyDiao. All rights reserved.
//

import UIKit

class ShareFreeListenVc: TTBaseVC {
    var type = 11
    let ShareTableViewCellID = "ShareTableViewCell"
    let ShareMyTableViewCellID = "ShareMyTableViewCell"
    
    lazy var listenModel = [ShareModel]()
    
    private lazy var tableView: TTTableView = {
        let tableView = TTTableView.init(frame: FRAME_CGFloat(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - OFFSET_TOP - 54), style: UITableView.Style.plain)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = WhiteBackColor
        tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
        tableView.showsVerticalScrollIndicator = false
        tableView.showsHorizontalScrollIndicator = false
        tableView.register(ShareTableViewCell.self, forCellReuseIdentifier: ShareTableViewCellID)
//        tableView.register(ShareMyTableViewCell.self, forCellReuseIdentifier: ShareMyTableViewCellID)
        tableView.tableFooterView = UIView.init(frame: FRAME_CGFloat(0, 0, SCREEN_WIDTH, 10))
        return tableView
    }()
    
    lazy var ruleView: ShareBackView = {
        let ruleView = ShareBackView.init(frame: FRAME_CGFloat(0, OFFSET_TOP, SCREEN_WIDTH, SCREEN_HEIGHT - OFFSET_TOP))
        return ruleView
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.title = "分享免费听"
        
        self.view.addSubview(self.tableView)
        setBottomView()
        setShareData()
        setRuleVie()
        
        let headImage = UIImageView.init(frame: FRAME_CGFloat(0, 0, SCREEN_WIDTH, SCREEN_SCALE_X(x: 150)))
        headImage.image = IMAGE(name: "ShareHead")
        headImage.addGestureRecognizer(UITapGestureRecognizer(target:self, action:#selector(headImageAction)))
        self.tableView.tableHeaderView = headImage
        headImage.isUserInteractionEnabled = true
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super .viewWillDisappear(animated)
//        ruleView.removeFromSuperview()
        ruleView.isHidden = true
        
    }
    
    

}

//  MARK: - ###### 方法 ######
extension ShareFreeListenVc {
    func setBottomView() {
        let share = ShareBottomView.init(frame: FRAME_CGFloat(0, SCREEN_HEIGHT - OFFSET_TOP - 54, SCREEN_WIDTH, 54))
        share.btnBlock = { (tag:Int) in
            self.type = tag
            if tag == 11 {
                self.setShareData()
            } else {
                self.setMyShareData()
            }
        }
        self.view.addSubview(share)
    }
    
    @objc func headImageAction() {
        ruleView.isHidden = false
    }
    
    func setRuleVie() {
        UIApplication.shared.keyWindow?.addSubview(ruleView)
        ruleView.isHidden = true
    }
}

//  MARK: - ###### 方法 ######
extension ShareFreeListenVc {
    func setShareData() {
        self.listenModel.removeAll()
        MTProgressHUD.show()
        WelfareRequestModel.loadShareData(parameters: ["startPoint":1,"maxPage":999]) { (success, mes, model) in
            if success && model != nil {
                self.listenModel = model!
            }
            
            if self.listenModel.count > 0 {
                self.tableView.setNoData(nodata: false)
            } else {
                self.tableView.setNoData(nodata: true)
            }
            MTProgressHUD.hidded(true)
            self.tableView.reloadData()
        }
    }
    
    func setMyShareData() {
        self.listenModel.removeAll()
        MTProgressHUD.show()
        WelfareRequestModel.loadMyShareData(jointArr: [String.getUserId()], parameters: ["startPoint":1,"maxPage":999]) { (success, mes, model) in
            if success && model != nil {
                self.listenModel = model!
                
            }
            
            if self.listenModel.count > 0 {
                self.tableView.setNoData(nodata: false)
            } else {
                self.tableView.setNoData(nodata: true)
            }
            MTProgressHUD.hidded(true)
            self.tableView.reloadData()
        }
    }
}

//  MARK: - ###### 协议 ######
extension ShareFreeListenVc: UITableViewDelegate, UITableViewDataSource, ShareMyTableViewCellDelegate, ShareTableViewCellDelegate {
    func shareToWX(cell: UITableViewCell) {
        let index:IndexPath = self.tableView.indexPath(for: cell) as! IndexPath
        let model = self.listenModel[index.row]
        
        toWX(model: model)
    }

    func shareActionDele(cell: UITableViewCell) {
        let index:IndexPath = self.tableView.indexPath(for: cell) as! IndexPath
        let model = self.listenModel[index.row]
        
        let vc = ShareDetailsVc()
        vc.programID = model.id
        PUSHVIEWCONTROLLER(vc)
    }
    
    func toWX(model:ShareModel) {
        HomeRequestModel.loadResourcesData(parameters: ["flg":"get_share_detail"]) { (success, message, urlStr) in
            if success {
                let shareUrl = urlStr + "?programId=\(model.id)&srcUserId=\(String.getUserId())"
                let share = ShareView.init(frame: FRAME_CGFloat(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT), title: model.title ?? "天天必听", des: model.describe ?? "分享免费听", url: shareUrl, image: model.shareImageUrl ?? "http://source.blistening.cn/bt_source/ttbt/logo/logo.png")
                UIApplication.shared.keyWindow?.addSubview(share)
            }
        }
        
        HomeRequestModel.UpdateMyProgramSharePost(parameters: ["programId":model.id,"userId":String.getUserId()]) { (success, message) in
            
        }
    }
    
    func freeActionDele(cell: UITableViewCell) {
        let index:IndexPath = self.tableView.indexPath(for: cell) as! IndexPath
        let model = self.listenModel[index.row]
        
        switch model.shareStatus {
        case "0":
            let playVc = PlayVC()
            playVc.id = model.id
            PUSHVIEWCONTROLLER(playVc)
        case "1":
            toWX(model: model)
        case "2":
            print("2")
        default:
            return
        }
        
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.listenModel.count
        
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 104
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if self.type == 11 {
            let cell = tableView.dequeueReusableCell(withIdentifier: ShareTableViewCellID) as! ShareTableViewCell
            cell.backgroundColor = UIColor.clear
            cell.selectionStyle = .none
            cell.delegate = self
            cell.indextLabel.text = "\(indexPath.row + 1)"
            cell.leftImage.sd_setImage(with: URL(string:(StringIncludeChineseToString(self.listenModel[indexPath.row].shareImageUrl ?? ""))), placeholderImage: IMAGE(name: "welfarePlace"), options: .lowPriority, completed: nil)
            cell.nameLabel.text = self.listenModel[indexPath.row].title ?? ""
            cell.titleLabel.text = self.listenModel[indexPath.row].describe ?? ""
            cell.numberLable.text = "\(self.listenModel[indexPath.row].listenNum)人免费拿"
            cell.priceLable.text = String.money(self.listenModel[indexPath.row].totalCount ?? 0.0)
            return cell
        } else {
//            let cell = tableView.dequeueReusableCell(withIdentifier: ShareMyTableViewCellID) as! ShareMyTableViewCell
            let cell:ShareMyTableViewCell = ShareMyTableViewCell.init(style: .default, reuseIdentifier: nil)
            cell.backgroundColor = UIColor.clear
            cell.selectionStyle = .none
            cell.delegate = self
            cell.indextLabel.text = "\(indexPath.row + 1)"
            cell.leftImage.sd_setImage(with: URL(string:(StringIncludeChineseToString(self.listenModel[indexPath.row].shareImageUrl ?? ""))), placeholderImage: IMAGE(name: "welfarePlace"), options: .lowPriority, completed: nil)
            cell.nameLabel.text = self.listenModel[indexPath.row].title ?? ""
            cell.setDate(shareTime: (self.listenModel[indexPath.row].shareCreateTime) / 1000, survivalTime: self.listenModel[indexPath.row].survivalTime / 1000)
//            cell.titleLabel.text = String.returnTimeTofammater(times: TimeInterval(self.listenModel[indexPath.row].survivalTime))
            if self.listenModel[indexPath.row].shareStatus == "0" {
                cell.setFree()
            } else if self.listenModel[indexPath.row].shareStatus == "1" {
                cell.setNext()
            } else if self.listenModel[indexPath.row].shareStatus == "2"{
                cell.setFail()
            } else {
                
            }
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = self.listenModel[indexPath.row]
        let playVc = PlayVC()
        playVc.id = model.id
        PUSHVIEWCONTROLLER(playVc)
  
    }
}
